﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Shapes;
using System.Windows.Media;
using MTDebug;
using nl.tno.ict.multitouch.wpfmultitouch.events;
using TouchLibEvents;
using System.ComponentModel;


namespace nl.tno.ict.multitouch.wpfmultitouch.controls
{
    public class MTGrid : Grid, MTObject, INotifyPropertyChanged
    {
        private Ellipse _el;
        private bool _fingerdown;
        private long _fingerID;
        private UCDebugInfo _debuginfo;
        public event TuioMoveFingerHandler SimulatedFingerMoved;
        public event TuioRemoveFingerHandler SimulatedFingerRemoved;
        public event TuioNewFingerHandler SimulatedNewFinger;
        private int _fingerCount;


        private int _timeout = 1000;
        public event NotMovedEventArgs NotMoved;
        public static readonly RoutedEvent MouseDoubleClickEvent;

        static MTGrid()
        {
           MTGrid.MouseDoubleClickEvent = EventManager.RegisterRoutedEvent("GridMouseDoubleClickEvent",
           RoutingStrategy.Bubble, typeof(RoutedEvent), typeof(MTCanvas));
        }

        public event RoutedEventHandler MouseDoubleClick
        {
            add { AddHandler(MTButton.MouseDoubleClickEvent, value); }
            remove { RemoveHandler(MTButton.MouseDoubleClickEvent, value); }
        }

        private bool _gesturesEnabled = true;
        /// <summary>
        /// Gets or sets a value if the gestures on the MTGrid must be recognised.
        /// </summary>
        public bool GesturesEnabled { get { return _gesturesEnabled; } set { _gesturesEnabled = value; } }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region region propertys

        private bool _debugEnabled = false;
        /// <summary>
        /// Set the debug property. 
        /// If true, a debuginfoscreen appears in the right corner 
        /// of the screen.
        /// </summary>
        public bool DebugEnabled
        {
            get
            {
                return _debugEnabled;
            }
            set
            {
                _debugEnabled = value;
                if (_debugEnabled)
                    this.showDebugInfo();
            }
        }
        private bool _simulationEnabled = false;
        /// <summary>
        /// Set the simulation property.
        /// If true, input (single point) with the mouse is possible.
        /// </summary>
        public bool SimulationEnabled
        {
            get
            {
                return _simulationEnabled;
            }
            set
            {
                _simulationEnabled = value;
                if (_simulationEnabled)
                    this.simulateInput();
            }
        }
        #endregion

        #region MTObject Members

        public bool CanBeScaled { get { return MTProperties.GetCanBeScaled(this); } set { MTProperties.SetCanBeScaled(this, value); } }
        public bool CanBeDragged { get { return MTProperties.GetCanBeDragged(this); } set { MTProperties.SetCanBeDragged(this, value); } }
        public bool CanBeClicked { get { return MTProperties.GetCanBeClicked(this); } set { MTProperties.SetCanBeClicked(this, value); } }
        public bool CanBeRotated { get { return MTProperties.GetCanBeRotated(this); } set { MTProperties.SetCanBeRotated(this, value); } }
        /// <summary>
        /// Gets or sets a bool that describes the value of a AdornersEnabledProperty for the element.
        /// </summary>
        public bool AdornersEnabled { get { return MTProperties.GetAdornersEnabled(this); } set { MTProperties.SetAdornersEnabled(this, value); } }

      
        
        #endregion

        /// <summary>
        /// The most important of the multitouch application. MTCanvas receives the multitouch events
        /// without a multitouch canvas your application wont work
        /// </summary>
        public MTGrid()
        {
            // Sets the TouchEnabledObjectProperty for the element always true.
            MTProperties.SetTouchEnabled(this, true);
            _fingerID = 0;
            this.Loaded += new RoutedEventHandler(MTGrid_Loaded);
            this.Background = new SolidColorBrush(Colors.White);//With a transparant background the simulation has an error.. (TODO)
            /*el = new Ellipse();
            el.Width = 10;
            el.Height = 10;
            el.Fill = new SolidColorBrush(Colors.Black);
            this.Children.Add(el);
            Canvas.SetLeft(el, 15);
            Canvas.SetTop(el, 15);
            Canvas.SetZIndex(el, 3);*/
        }

        void MTGrid_Loaded(object sender, RoutedEventArgs e)
        {
            /*if (SimulatedFingerMoved != null)
            {
                SimulatedFingerMoved(sender,
                     new TuioMoveFingerEventArgs(new FingerObject()
                     {
                         position = new Point(182, 477),
                         Id = _fingerID
                     }));
            }
            _fingerID++;*/
        }

        //public bool GestureModuleEnabled { get { return _gesturModuleEnabled; } set { GestureModuleEnabled = value; } }

        public bool IsDragging
        {
            get { return MTProperties.GetIsDragging(this); }
            set { MTProperties.SetIsDragging(this, value); }

        }

        public bool IsScaling
        {
            get { return MTProperties.GetIsScaling(this); }
            set
            {
                MTProperties.SetIsScaling(this, value);
                if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("IsScaling"));
            }
        }

        public bool IsRotating
        {
            get { return MTProperties.GetIsRotating(this); }
            set { MTProperties.SetIsRotating(this, value); }
        }

        /// <summary>
        /// If debug property is true, the debug info screen will always appear in the upper right corner of 
        /// the screen. 
        /// </summary>
        public void PositioningDebugInfo()
        {
            if (_debuginfo != null)
            {
                Canvas.SetTop(_debuginfo, 0);
                Canvas.SetLeft(_debuginfo, this.ActualWidth - _debuginfo.ActualWidth);
            }
        }

        /// <summary>
        /// If the simulate input property is true, the simulateInput will be used to catch the mouse events and
        /// draw a small ellipse under the mouse pointer
        /// </summary>
        private void simulateInput()
        {
            /*_el = new Ellipse();
            _el.Height = 10;
            _el.Width = 10;
            _el.Fill = new SolidColorBrush(Colors.Black);
            Canvas.SetZIndex(_el, 20);
            this.Children.Add(_el);*/
            this.PreviewMouseMove += new System.Windows.Input.MouseEventHandler(MTGrid_PreviewMouseMove); 
            this.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(MTGrid_PreviewMouseLeftButtonDown); //+= new System.Windows.Input.MouseButtonEventHandler(MTCanvas_MouseLeftButtonDown);
            this.PreviewMouseLeftButtonUp += new System.Windows.Input.MouseButtonEventHandler(MTGrid_PreviewMouseLeftButtonUp); //+= new System.Windows.Input.MouseButtonEventHandler(MTCanvas_MouseLeftButtonUp);
        }

        public void MTGrid_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            _fingerdown = false;
            if (SimulatedFingerMoved != null)
            {
                SimulatedFingerRemoved(sender, new TuioRemoveFingerEventArgs(_fingerID));
                _fingerID++;
            }
            e.Handled = true;
        }

        public void MTGrid_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            _fingerdown = true;
            if (SimulatedFingerMoved != null)
            {
                SimulatedFingerMoved(sender,
                     new TuioMoveFingerEventArgs(new FingerObject()
                     {
                         CurrentPosition = new Point(e.GetPosition(this).X, e.GetPosition(this).Y),
                         Id = _fingerID
                     }));
            }
            e.Handled = true;
        }

        public void MTGrid_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (_fingerdown && SimulatedFingerMoved != null)
            {
                 SimulatedFingerMoved(sender,
                 new TuioMoveFingerEventArgs(new FingerObject()
                 {
                     CurrentPosition = new Point(e.GetPosition(this).X, e.GetPosition(this).Y),
                     Id = _fingerID
                 }));
            }
            e.Handled = true;
        }

        /// <summary>
        /// If the showdebuginfo property is true, this method will be used to make a new instance of de UCDebugInfo(usercontrol)
        /// Use the method "Write" to write output to the screen.
        /// </summary>
        private void showDebugInfo()
        {
            //add UCDebugInfo screen here;
            _debuginfo = new UCDebugInfo();
            this.Children.Add(_debuginfo);
            // _processing.newDebugInfo += new DebugInfoHandler(_processing_newDebugInfo);

        }

        /// <summary>
        /// If the Debug property is true, this method can be used to write output to the 
        /// debug info screen in the upper right corner of the canvas
        /// </summary>
        /// <param name="output">The input string</param>
        public void Write(string input)
        {
            if (_debugEnabled)
                _debuginfo.OutputWrite(input);
        }

        /// <summary>
        /// Set the amount of fingers in the debug info screen in the upper right corner of the canvas
        /// </summary>
        /// <param name="fingercount"></param>
        public void SetFingerCount(int fingercount)
        {
            if (_debugEnabled)
                _debuginfo.SetFingerCount(fingercount);
        }

        /// <summary>
        /// Get the left count of pixels from the desktop to window
        /// </summary>
        /// <returns>Amount of left pixels</returns>
        public double Left()
        {
            if (Parent is Window) return ((Window)Parent).Left;
            return 0.0;
        }

        /// <summary>
        /// Get the top count of pixels from the desktop to window
        /// </summary>
        /// <returns>Amount of left pixels</returns>
        public double Top()
        {
            if (Parent is Window) return ((Window)Parent).Top;
            return 0.0;
        }

        /// <summary>
        /// Close the nl.tno.ict.multitouch.framework.tuio listener thread
        /// </summary>
        public void Disconnect()
        {
            //_processing.Disconnect();
        }

            

        #region MTObject Members

        /// <summary>
        /// Gets or sets the timeout, in ms, used to by the NotMoved event. Default: 1000 ms
        /// </summary>
        int MTObject.Timeout
        {
            get { return _timeout; }
            set { _timeout = value; }
        }

        void MTObject.NotMoved()
        {
            if (NotMoved != null)
                NotMoved(this, new EventArgs());
        }

        public int FingerCount
        {
            get
            {
                return _fingerCount;
            }
            set
            {
                _fingerCount = value;
            }
        }
        /// <summary>
        /// Gets or sets the onTop dependency property. When true, when a finger touches the object the object
        /// gets on top of the screen (z-index changes).
        /// </summary>
        public bool OnTop
        {
            get { return MTProperties.GetOnTop(this); }
            set { MTProperties.SetOnTop(this, value); }
        }

        /// <summary>
        /// Set the object TouchEnabled. When an object isn't touchEnabled interaction with fingers is not
        /// possible (nothing will happen).
        /// </summary>
        public bool TouchEnabled
        {
            get { return MTProperties.GetTouchEnabled(this); }
            set { MTProperties.SetTouchEnabled(this, value); }
        }

        #endregion
    }
}
